package com.ycy.ss.sync;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.google.api.client.http.json.JsonHttpRequest;
import com.google.api.client.http.json.JsonHttpRequestInitializer;
import com.google.api.services.plus.Plus;
import com.google.api.services.plus.PlusRequest;
import com.google.api.services.plus.model.Activity;
import com.google.api.services.plus.model.ActivityFeed;
import com.google.api.services.plus.model.Activity.PlusObject.Attachments;
import com.ycy.ss.Constant;
import com.ycy.ss.status.AllStatus;
import com.ycy.ss.tumblr.TumblrUtil;
import com.ycy.ss.tumblr.po.TumblrPostAnswer;
import com.ycy.ss.tumblr.po.TumblrPostAudio;
import com.ycy.ss.tumblr.po.TumblrPostBase;
import com.ycy.ss.tumblr.po.TumblrPostChat;
import com.ycy.ss.tumblr.po.TumblrPostLink;
import com.ycy.ss.tumblr.po.TumblrPostPhotos;
import com.ycy.ss.tumblr.po.TumblrPostQuote;
import com.ycy.ss.tumblr.po.TumblrPostText;
import com.ycy.ss.tumblr.po.TumblrPostVideo;
import com.ycy.util.GoogleUtil;

public class ReadInfo{
	private static Logger logger = LogManager.getLogger(ReadInfo.class);

	public static List<Info> read(String siteName){
		if ("tumblr".equals(siteName)) {
			return _readTumblr();
		} else if ("google".equals(siteName)) {
			return _readGoogle();
		} else if ("sina".equals(siteName)) {
			return _readSina();
		}
		return null;
	}

	private static List<Info> _readTumblr(){
		List<Info> res = new ArrayList<Info>();
		logger.info("read info from tumblr.");
		if (AllStatus.tumblr == null) {
			logger.warn("AllStatus.tumblr is null.");
		} else {
			// 限制limit等
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("limit", "5");
			paramMap.put("filter", "text");

			try {
				List<TumblrPostBase> postList = TumblrUtil.queryPosts(AllStatus.tumblr.ACCESS_TOKEN, Constant
						.getAccountInfo("tumblr.baseHostname"), paramMap);
				Collections.reverse(postList);

				logger.info("read info from tumblr,postList.size=" + postList.size());
				for (TumblrPostBase post : postList) {
					String lastId = post.getDate();
					String LAST_ID = AllStatus.tumblr.LAST_ID;

					logger.info("read info from tumblr,AllStatus.tumblr.LAST_ID=" + AllStatus.tumblr.LAST_ID
							+ "::lastId=" + lastId);
					if (lastId != null
							&& (lastId.length() > LAST_ID.length() || (lastId.length() == LAST_ID.length() && lastId
									.compareTo(LAST_ID) > 0))) {
						String type = post.getType();
						Info info = new Info();
						info.setFromSite("tumblr");
						info.setType(TumblrUtil.typeToAllType(type));
						info.setInfoUrl(post.getPost_url());
						info.setTags(post.getTags());

						if (AllType.TEXT.equals(type)) {
							TumblrPostText text = (TumblrPostText) post;
							String title = text.getTitle();
							String body = text.getBody();

							String content = ((title != null && title.length() != 0) ? title + " - " : "") + body;
							info.setContent(content);

							// FIXME del
							// logger.error(":::read from tumblr,text:"+content);
						} else if ("quote".equals(type)) {
							TumblrPostQuote quote = (TumblrPostQuote) post;
							logger.warn("_readTumblr,type is:" + type);
							continue;
						} else if ("chat".equals(type)) {
							TumblrPostChat chat = (TumblrPostChat) post;
							logger.warn("_readTumblr,type is:" + type);
							continue;
						} else if (AllType.LINK.equals(type)) {
							TumblrPostLink link = (TumblrPostLink) post;

							String content = link.getTitle();
							info.setContent(content);
							info.setAttachmentUrl(link.getUrl());
						} else if ("answer".equals(type)) {
							TumblrPostAnswer answer = (TumblrPostAnswer) post;
							logger.warn("_readTumblr,type is:" + type);
							continue;
						} else if (AllType.VIDEO.equals(type)) {
							TumblrPostVideo video = (TumblrPostVideo) post;
							String caption = video.getCaption();
							String player = "";
							if (video.getPlayer().size() != 0) {
								player = video.getPlayer().get(0).getEmbed_code();
							}

							String content = ((caption != null && caption.length() != 0) ? caption + " - " : "")
									+ player;
							info.setContent(content);
						} else if (AllType.AUDIO.equals(type)) {
							TumblrPostAudio audio = (TumblrPostAudio) post;
							String caption = audio.getCaption();
							String player = audio.getPlayer();

							String content = ((caption != null && caption.length() != 0) ? caption + " - " : "")
									+ player;
							info.setContent(content);
						} else if (AllType.PHOTO.equals(type)) {
							TumblrPostPhotos photos = (TumblrPostPhotos) post;

							String caption = photos.getCaption();
							info.setContent(caption);
							info.setAttachmentUrl(photos.getFirstPhotoUrl());

							// FIXME del
							// logger.error(":::read from tumblr,photo:"+caption);
						} else {
							logger.warn("_readTumblr failed,type is:" + type);
							continue;
						}

						logger.info("read info from tumblr,add ok,lastId=" + lastId);
						res.add(info);
						AllStatus.tumblr.readOk(lastId);
					}
				}
			} catch (Exception e) {
				logger.warn("", e);
				AllStatus.tumblr.error(e.getMessage());
			}
		}
		logger.info("read info from tumblr ok.");
		return res;
	}

	private static List<Info> _readGoogle(){
		List<Info> res = new ArrayList<Info>();
		logger.info("read info from google.");
		if (AllStatus.google == null) {
			logger.warn("AllStatus.google is null.");
		} else {
			Plus.Activities.List listActivities = null;
			try {
				Plus.Builder builder = new Plus.Builder(GoogleUtil.TRANSPORT, GoogleUtil.JSON_FACTORY, null);
				Plus unauthenticatedPlus = builder.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer(){
					public void initialize(JsonHttpRequest jsonHttpRequest) throws IOException{
						PlusRequest plusRequest = (PlusRequest) jsonHttpRequest;
						plusRequest.setKey(Constant.getAccountInfo("google.google_api_key"));
					}
				}).build();
				
				listActivities = unauthenticatedPlus.activities().list("me", "public");
//				listActivities = unauthenticatedPlus.activities().list(Constant.getAccountInfo("google.user_id"), "public");
//				listActivities = AllStatus.google.PLUS.activities().list("me", "public");
			} catch (IOException e) {
				logger.error("", e);
				return Collections.EMPTY_LIST;
			}
			listActivities.setMaxResults(5L);
			ActivityFeed activityFeed;
			try {
				activityFeed = listActivities.execute();
				List<Activity> activities = activityFeed.getItems();
				Collections.reverse(activities);

				logger.info("read info from google,activities.size=" + activities.size());
				for (Activity activity : activities) {
					String lastId = activity.getUpdated().toString();
					String LAST_ID = AllStatus.google.LAST_ID;

					logger.info("read info from google,AllStatus.google.LAST_ID=" + AllStatus.google.LAST_ID
							+ "::lastId=" + lastId);
					if (lastId != null
							&& (lastId.length() > LAST_ID.length() || (lastId.length() == LAST_ID.length() && lastId
									.compareTo(LAST_ID) > 0))) {

						String verb = activity.getVerb();
						List<Attachments> attachments = activity.getObject().getAttachments();
						String type = GoogleUtil.attachmentToAllType(attachments);
						Info info = new Info();
						info.setFromSite("google");
						info.setType(type);
						info.setInfoUrl(activity.getUrl());

						String annotation = activity.getAnnotation();

						if (AllType.TEXT.equals(type)) {
							String content = ((annotation != null && annotation.length() != 0) ? annotation + " - "
									: "")
									+ activity.getObject().getContent();
							info.setContent(content);
						} else if (AllType.PHOTO.equals(type)) {
							String content = "";
							String attachmentUrl = "";

							Attachments firstAttachment = attachments.get(0);
							if (attachments.size() >= 2 && !"photo".equals(firstAttachment.getObjectType())
									&& "photo".equals(attachments.get(1).getObjectType())) {
								content = ((annotation != null && annotation.length() != 0) ? annotation + " - " : "")
										+ ((activity.getObject().getContent() != null && activity.getObject()
												.getContent().length() != 0) ? activity.getObject().getContent()
												+ " - " : "") + firstAttachment.getDisplayName();
								attachmentUrl = attachments.get(1).getFullImage().getUrl();
							} else if ("photo".equals(firstAttachment.getObjectType())) {
								content = ((annotation != null && annotation.length() != 0) ? annotation + " - " : "")
										+ activity.getObject().getContent();
								attachmentUrl = firstAttachment.getFullImage().getUrl();
							}
							info.setContent(content);
							info.setAttachmentUrl(attachmentUrl);
						} else if (AllType.LINK.equals(type)) {
							String content = ((annotation != null && annotation.length() != 0) ? annotation + " - "
									: "")
									+ ((activity.getObject().getContent() != null && activity.getObject().getContent()
											.length() != 0) ? activity.getObject().getContent() + " - " : "")
									+ attachments.get(0).getDisplayName();

							info.setContent(content);
							info.setAttachmentUrl(attachments.get(0).getUrl());
						} else {
							logger.warn("_readGoogle failed,type is:" + type);
							continue;
						}

						logger.info("read info from google,add ok,lastId=" + lastId);
						res.add(info);
						AllStatus.google.readOk(lastId);
					}
				}
			} catch (Exception e) {
				logger.warn("", e);
				AllStatus.google.error(e.getMessage());
			}
		}
		return res;
	}

	// FIXME
	private static List<Info> _readSina(){
		List<Info> res = new ArrayList<Info>();
		logger.info("read info from sina.");
		if (AllStatus.sina == null) {
			logger.warn("AllStatus.sina is null.");
		} else {

		}
		return res;
	}

}
